package leetcode;

import java.util.Arrays;

/**
 * Created by Ghost on 2014/12/4 0004.
 */
public class _3Sum_Closest {
    public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int min = Integer.MAX_VALUE;
        int sum = 0;
        for(int i=0;i<num.length-1;i++){
            if(i>0 && num[i]==num[i-1])
                continue;
            int left = i+1,right = num.length-1;
            int tar = target-num[i];
            while(left<right){
                int abs = Math.abs(tar-(num[left]+num[right]));
                if(abs<min){
                    min = abs;
                    sum  = num[i]+num[left]+num[right];
                }
                if(tar>(num[left]+num[right])){
                    left++;
                }
                else if(tar<(num[left]+num[right])){
                    right--;
                }
                else{
                    min = 0;
                    sum = num[i]+num[left]+num[right];
                    break;
                }
            }
        }
        return sum;
    }

    public static void main(String[] args){
        _3Sum_Closest sum_closest = new _3Sum_Closest();
        int[] num = {0,2,1,-3};
        System.out.println(sum_closest.threeSumClosest(num,1));
    }
}
